package cc.ucanuup.service.blog.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import cc.ucanuup.common.AppConsts;
import cc.ucanuup.common.support.easyui.inter.EasyuiQuery;
import cc.ucanuup.service.blog.dao.ArticleJPA;
import cc.ucanuup.service.blog.dto.ArticleDto;
import cc.ucanuup.service.blog.entity.Article;
import cc.ucanuup.service.blog.inter.ArticleService;

@Service
public class ArticleServiceImpl implements ArticleService {
	
	@Autowired
	private ArticleJPA  articleJPA;

	@Override
	public Article save(Article entity) {
		return articleJPA.save(entity);
	}

	@Override
	public Page<Article> queryArticleList(EasyuiQuery query,final ArticleDto dto) {
		
		String[] sorts = query.getSortArr();
		String[] oders = query.getOrders();
		List<Order> orders = new ArrayList<Order>();
		Sort sort = null;
		if (sorts != null && sorts.length > 0) {
			Order od = null;
			for (int i = 0; i < sorts.length; i++) {
				if ("asc".equals(oders[i])) {
					od = new Order(Direction.ASC, sorts[i]);
				} else {
					od = new Order(Direction.DESC, sorts[i]);
				}
				orders.add(od);
			}
			sort = new Sort(orders);
		}
		PageRequest pageable = new PageRequest(query.getPageNo(), query.getPageSize(), sort);
		Specification<Article> specification = new Specification<Article>() {

			@Override
			public Predicate toPredicate(Root<Article> root,
					CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {

				List<Predicate> list = new ArrayList<Predicate>();
				Predicate deleted = criteriaBuilder.equal(root.get("deleted"), AppConsts.DELETED_EXIST);
				list.add(deleted);

/*				if (map.get("dicDesc") != null) {
					Predicate dicDesc = criteriaBuilder.like(root.get("dicDesc").as(String.class),
							"%" + (String) map.get("dicDesc") + "%");
					list.add(dicDesc);
				}
				if (map.get("dicCode") != null) {
					Predicate dicCode = criteriaBuilder.equal(root.get("dicCode"), map.get("dicCode"));
					list.add(dicCode);
				}*/
				Predicate[] p = new Predicate[list.size()];
				return criteriaBuilder.and(list.toArray(p));
			}
		};
		Page<Article> sourceCodes = articleJPA.findAll(specification, pageable);
		return sourceCodes;
	}

}
